package ln;

import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;

import dao.DaoOp;
import excepciones.FiltroTarjetaException;
import on.*;
import util.Basededatos;

/**
 * Gestion Operaciones
 * 
 * @author lgonzalez
 * @version 1.0 15-05-2013
 * @since 15-05-2013
 *
 */
public class GestorOp {

	public boolean suma(Tarjeta tar, double cantidad, String observacion)
			throws SQLException {
		Connection miCon = Basededatos.establecerConexion();
		miCon.setAutoCommit(false);

		if (new DaoOp().suma(miCon, tar, cantidad, observacion) == 1) {
			miCon.commit();
			miCon.close();
			return true;
		} else {
			miCon.rollback();
			miCon.close();
			return false;
		}

	}

	public boolean resta(Tarjeta tar, double cantidad, String observacion)
			throws SQLException, FiltroTarjetaException {
		if (this.consSaldo(tar) < cantidad) {
			throw new FiltroTarjetaException("SIN CREDITO");
		}
		Connection miCon = Basededatos.establecerConexion();
		miCon.setAutoCommit(false);

		if (new DaoOp().resta(miCon, tar, cantidad, observacion) == 1) {
			miCon.commit();
			miCon.close();
			return true;
		} else {
			miCon.rollback();
			miCon.close();
			return false;
		}
	}

	public ArrayList<Operacion> consOp(Tarjeta tar) throws SQLException,
			ParseException {
		ArrayList<Operacion> listOp = null;
		Connection miCon = Basededatos.establecerConexion();
		miCon.setAutoCommit(false);
		listOp = new DaoOp().consOp(miCon, tar, null, null, null);
		miCon.commit();
		miCon.close();
		return listOp;
	}

	public ArrayList<Operacion> consOp(Cliente cli) throws SQLException,
			ParseException {
		ArrayList<Operacion> listOp = null;
		Connection miCon = Basededatos.establecerConexion();
		miCon.setAutoCommit(false);
		listOp = new DaoOp().consOp(miCon, null, cli, null, null);
		miCon.commit();
		miCon.close();
		return listOp;
	}

	public ArrayList<Operacion> consOp(Tarjeta tar, Date inicio, Date fin)
			throws SQLException, ParseException {
		ArrayList<Operacion> listOp = null;
		Connection miCon = Basededatos.establecerConexion();
		miCon.setAutoCommit(false);
		listOp = new DaoOp().consOp(miCon, tar, null, inicio, fin);
		miCon.commit();
		miCon.close();
		return listOp;
	}

	public double consSaldo(Tarjeta Tar) throws SQLException {
		Connection miCon = Basededatos.establecerConexion();
		miCon.setAutoCommit(false);
		Double Saldo = new DaoOp().consSaldo(miCon, Tar);
		miCon.commit();
		miCon.close();
		return Saldo;
	}
}
